package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HZ {
    // 惠泽没有账号，不可用
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO HZ############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            // page.navigate(site.getSiteUrl());
            page.navigate("http://www.dfhyy.com");
            page.click("input[name=\"userName\"]");
            // Fill input[name="userName"]
            page.waitForTimeout(1500);
            page.fill("input[name=\"userName\"]", site.getUserName());
            // Press Enter

            // page.press("input[name=\"userName\"]", "Enter");
            // Click input[name="password"]

            page.click("input[name=\"password\"]");
            // Fill input[name="password"]
            page.fill("input[name=\"password\"]", site.getPassWord());
            // page.check("#autologin");
            // Press Enter
            // page.waitForNavigation(new
            // Page.WaitForNavigationOptions().setUrl("http://bh.ry600.com/_shop/index.shtml"),
            // () ->
            page.waitForNavigation(() -> {
                page.press("input[name=\"password\"]", "Enter");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO HZ#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM RY########");

        List<Result> res = getList(site, search);
        log.info("END OF fetch product");
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        log.info(Integer.toString(res.size()));
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        return res;
    }

    public static List<Result> getList(Site site, SearchDTO search) {

        List<Result> list = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            page.navigate(site.getSiteUrl());
            log.info("**********");
            log.info(search.getKeywordStr());
            log.info("**********");

            // page.waitForTimeout(5500);
            // String st = page.innerHTML(".dialog-adv-div");
            // log.info(st);

            // page.click(".delelte-dialog-adv img", new
            // Page.ClickOptions().setForce(true));
            // page.click("div:nth-child(100) .dialog-adv-content .delelte-dialog-adv img");

            // page.check("text=知道了");

            page.click("text=热门搜索抢购阿莫西林搜 索搜本店 >> input[name=\"search_text\"]");
            page.fill("text=热门搜索抢购阿莫西林搜 索搜本店 >> input[name=\"search_text\"]", search.getKeywordStr());
            page.waitForNavigation(() -> {
                page.click("text=搜 索");
            });

            // String wait = page.textContent(".spxsjSpanCss");
            log.info("HERE IS THE WAIT PART");
            page.waitForTimeout(1500);
            String content = page.innerHTML(".p-list");
            log.info("HERE IS THE CONTENT PART");
            // log.info(content);

            Document doc = Jsoup.parseBodyFragment(content);
            Element body = doc.body();

            Elements lis = body.getElementsByClass("pl-skin");

            if (lis.size() == 0) {
                log.info("DZ HAVE NO RESULTS");
                return list;
            }

            for (Element li : lis) {

                Elements els = li.getElementsByClass("p-caption");
                Element item = els.first().getElementsByTag("a").first();
                String pName = item.text();
                String orderUrl = item.attributes().get("href");
                // log.info("商品名是:" + pName);

                Element priceTag = li.getElementsByClass("price-msg").first();
                String sourcePrice = priceTag.getElementsByTag("em").first().text();

                // String sourcePrice =
                // li.getElementsByClass("carousel__item--price").first().text();
                String sourcePriceClean = sourcePrice;
                // log.info("价格是:" + sourcePriceClean);
                // String amountLeft = li.getElementsByClass("flex_hei").first().text();

                Double priceDouble = NumberUtil.isNumber(sourcePriceClean) ? Double.parseDouble(sourcePriceClean) : 0;
                // log.info("数字价格是:" + priceDouble.toString());

                // log.info("商品购买URL是:" + orderUrl);

                // String partnerCode = site.getSiteNo() + sourceCodeClean;

                Result re = new Result();
                re.setKeywordStr(search.getKeywordStr());
                re.setProductName(pName);
                // sourceProducer));
                re.setOrderUrl(StrUtil.concat(true, site.getSiteUrl(), orderUrl));
                re.setScanTime(TimeUtil.currentTime());
                re.setSearchId(search.getId());
                re.setSiteName("荣药");
                // // // re.setSiteId("");
                re.setSiteNo("RY");
                re.setScanPrice(sourcePriceClean);

                re.setPrice(priceDouble);
                re.setStatus(0);

                // // // resultDao.save(re);
                list.add(re);

            }

            // return "SUCCESS";
            log.info("WORM HZ SUCCESS");

        } catch (RuntimeException e) {
            log.info(e.toString());
            log.info("WORM HZ FAILED");
        }

        // Result r = new Result();
        // r.setKeywordStr("KEY_WD");
        // r.setOrderUrl("ORDER_URL");
        // list.add(r);
        return list;
    }
}
